<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input
          v-model="queryParams.roleKey"
          placeholder="请输入权限字符"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="showBtn">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >
          修改
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >
          删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:role:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色编号" prop="roleId" width="120" />
      <el-table-column
        label="角色名称"
        prop="roleName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="权限字符"
        prop="roleKey"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="显示顺序" prop="roleSort" width="100" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
          <!-- <span>{{ parseTime(scope.row.createTime) }}</span> -->
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="showBtn"
      >
        <template #default="scope">
          <el-tooltip
            content="修改"
            placement="top"
            v-if="scope.row.roleId !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:role:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
            v-if="scope.row.roleId !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']"
            ></el-button>
          </el-tooltip>

          <!-- <el-tooltip
            content="分配菜单"
            placement="top"
            v-if="scope.row.roleId !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Menu"
              @click="handleAllocateMenu(scope.row)"
              v-hasPermi="['system:role:allocation']"
            ></el-button>
          </el-tooltip> -->
          <!-- <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">
                <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
                <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>

    <div
      v-if="!showBtn"
      class="dialog-footer"
      style="text-align: right; margin-top: 16px"
    >
      <el-button @click="$emit('confirm', ids)" type="primary">确定</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </div>

    <pagination
      v-if="showBtn"
      v-show="total > 0"
      :total="total"
      v-model:page="pageIndex"
      v-model:limit="pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <span>
              <el-tooltip
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
          >
            展开/折叠
          </el-checkbox>
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
          >
            全选/全不选
          </el-checkbox>
          <el-checkbox label="父子联动" :value=true border disabled />
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuRef"
            node-key="menuId"
            :check-strictly="form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'menuName', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配菜单弹框 -->
    <el-dialog
      v-model="menuDialogVisible"
      title="分配菜单"
      width="70%"
      @closed="menuDialogVisible = false"
    >
      <menu-sub
        ref="menuRef"
        :roleId="currentRoleId"
        mode="assign"
        @confirm="handleMenuConfirm"
        @cancel="menuDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  toRefs,
  getCurrentInstance,
  nextTick,
} from 'vue'
import type { TableInstance } from 'element-plus'

import MenuSub from '@/views/acl/menu/index.vue'
// import type { ElTree } from 'element-plus'
import {
  reqPageRoles,
  reqRoleOne,
  reqRoleAdd,
  reqRoleUpdate,
  reqRoleDel,
} from '@/api/role/index'
import { Role, RolePageResponse } from '@/api/role/type'
import { R, page, PageQuery, ResponseData, PageInfo } from '@/api/common/type'
import { reqAssignedMenu, reqMenuTree } from '@/api/menu/index'
import { Menu } from '@/api/menu/type'
import { requserOne } from '@/api/users/index'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'

const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const menuOptions = ref<Menu[]>([])
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const deptExpand = ref(true)
const deptNodeAll = ref(false)
const deptOptions = ref([])
const openDataScope = ref(false)
const menuRef = ref<null>(null)
const deptRef = ref(null)
const showBtn = ref(true)
const tableRef = ref<TableInstance>()
const { proxy } = getCurrentInstance()

const menuDialogVisible = ref(false)
const currentRoleId = ref<number | null>(null)

const pageIndex = ref(1)
const pageSize = ref(10)

const props = defineProps<{
  userId: number
}>()
const emit = defineEmits<{
  confirm: [ids: number[]]
  cancel: []
}>()

// 组件挂载时加载数据
onMounted(async () => {
  await getList() // 先拉角色列表
  console.log('dialog userId==>', props.userId)

  if (props.userId != null && props.userId !== -1) {
    showBtn.value = false
    try {
      // 1. 等待用户详情
      const res = await requserOne(props.userId)
      const user = res.data // 取出用户实体
      // 2. 取出已有角色 id 数组
      const ownedRoles: Role[] = user.roles ?? []

      // 3. 等 DOM 渲染完再勾选
       nextTick(() => {
        const roleIdSet = new Set(ownedRoles.map((r) => r.roleId) ?? [])
        roleList.value.forEach((row) => {
          console.log('row==', row.roleId, roleIdSet)
          if (roleIdSet.has(row.roleId)) {
            tableRef.value?.toggleRowSelection(row, true)
          }
        })
      })
    } catch (e) {
      console.error(e)
      ElMessage.error('获取用户角色失败')
    }
  }
})

const sys_normal_disable = reactive([
  {
    label: '启用',
    value: '0',
  },
  {
    label: '禁用',
    value: '1',
  },
])

const roleList = ref<Role[]>([])

const queryParams = reactive({
  roleName: '',
  roleKey: '',
  status: '',
})

const data = reactive({
  form: {
    roleId: null,
    roleName: '',
    roleKey: '',
    roleSort: 0,
    status: '0',
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: '',
  },
  rules: {
    roleName: [
      { required: true, message: '角色名称不能为空', trigger: 'blur' },
    ],
    roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
    roleSort: [
      { required: true, message: '角色顺序不能为空', trigger: 'blur' },
    ],
  },
})

const { form, rules } = toRefs(data)

/** 查询角色列表 */
const getList = async () => {
  loading.value = true
  const pageInfo: PageInfo = {
    pageSize: pageSize.value,
    pageIndex: pageIndex.value,
  }
  const role: Role = { ...queryParams }
  if (dateRange.value.length > 1) {
    role.beginTime = dateRange.value[0] + 'T00:00:00'
    role.endTime = dateRange.value[1] + 'T23:59:59'
  }
  const query: PageQuery<Role> = {
    filterData: role,
    pageInfo: pageInfo,
  }
  const result: RolePageResponse = await reqPageRoles(query)

  if (result.code === 200) {
    roleList.value = result.data.records
    total.value = result.data.total
  } else {
    return Promise.reject(new Error(result.message))
  }

  loading.value = false
}

/** 提交按钮 */
const submitForm = async () => {
  proxy.$refs['roleRef'].validate((valid: any) => {
    if (!valid) {
      proxy.$modal.msgSuccess('存在不合法的参数！')
      return
    }
  })

  if (form.value.roleId != null) {
    form.value.menuIds = getMenuAllCheckedKeys()
    console.log('form update ===>', form.value)
    const result: R<boolean> = await reqRoleUpdate(form.value)
    if (result && result.code === 200) {
      const role: Role = await getRoleMenuTreeselect(form.value.roleId)
      console.log('role ========>', role)
      roleList.value.map((m) => (m.roleId === role.roleId ? role : m))
      roleList.value = roleList.value.map((item) =>
        item.roleId === role.roleId ? role : item,
      )
      proxy.$modal.msgSuccess('更新成功')
      open.value = false
      return
    }
    proxy.$modal.msgSuccess('更新失败！')
    open.value = false
    // getList()
  } else {
    form.value.menuIds = getMenuAllCheckedKeys()
    const result: R<boolean> = await reqRoleAdd(form.value)
    if (result && result.code === 200) {
      proxy.$modal.msgSuccess('新增成功')
      open.value = false
      getList()
      return
    }

    proxy.$modal.msgSuccess('新增失败！')
    open.value = false
  }
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    // menuRef.value.setCheckedKeys([])
  }
  menuExpand.value = false
  menuNodeAll.value = false
  deptExpand.value = true
  deptNodeAll.value = false
  form.value = {
    roleId: null,
    roleName: '',
    roleKey: '',
    roleSort: 0,
    status: '0',
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: false,
    deptCheckStrictly: true,
    remark: '',
  }
  // proxy.resetForm("roleRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log('queryParams ===>', queryParams)
  console.log('date ===> ', dateRange.value)
  getList()
  loading.value = false
}

/** 重置按钮操作 */
function resetQuery() {
  pageSize.value = 10
  pageIndex.value = 1
  queryParams.roleName = ''
  ;(queryParams.roleKey = ''), (queryParams.status = ''), (dateRange.value = [])
  handleQuery()
  loading.value = false
}

/** 添加角色 */
function handleAdd() {
  reset()
  getMenuTreeselect()
  open.value = true
  title.value = '添加角色'
}

/** 查询菜单树结构 */
const getMenuTreeselect = async () => {
  const result: R<Menu[]> = await reqMenuTree()
  menuOptions.value = result.data
}

/** 修改角色 */
/** 修改角色 */
async function handleUpdate(row: Role) {
  reset()
  const roleId = row.roleId
  getMenuTreeselect()

  /* 1. 等待 Promise  resolve */
  const menus = await getRoleMenuTreeselect(roleId)

  /* 2. 现在 menuIds 是数组，可以遍历 */
  open.value = true
  nextTick(() => {
    console.log('menuIds ===== >', menus)
    // 1. 先清空
    // menuRef.value.setCheckedKeys([])
    // 2. 逐条设置（自动处理父子关系）
    menus.menus?.forEach((key) => menuRef.value!.setChecked(key, true, false))
  })

  form.value = { ...menus }
  title.value = '修改角色'
}

/** 根据角色ID查询菜单树结构 */
const getRoleMenuTreeselect = async (roleId: number) => {
  const result: R<Role> = await reqRoleOne(roleId)

  if (!result) {
    return {}
  }

  return result.data
}

/** 删除按钮操作 */
const handleDelete = async (row: { roleId?: number | number[] }) => {
  // 1. 取到本次要删的 id 或 ids
  const raw = row.roleId ?? ids.value // 支持行内/批量两种入口

  // 2. 统一转成数组
  const roleIds = Array.isArray(raw) ? raw : [raw]

  await reqRoleDel(roleIds) // 等待真正删完

  proxy.$modal.msgSuccess('删除成功')

  await getList()
  // 再拿最新数据
  loading.value = false
}

/** 导出按钮操作 */
function handleExport() {
  // proxy.download("system/role/export", {
  //   ...queryParams.value,
  // }, `role_${new Date().getTime()}.xlsx`)
}

/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map((item) => item.roleId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 分配用户 */
function handleAllocateMenu(row: { roleId: number | null }) {
  // router.push("/system/role-auth/user/" + row.roleId)
  currentRoleId.value = row.roleId
  menuDialogVisible.value = true
}

/** 子组件点击“确定”回调 */
const handleMenuConfirm = async(menuIds: number[]) => {
  // 这里把 menuIds 与当前角色绑定，示例直接打印
  console.log(`角色 ${currentRoleId.value} 绑定菜单：`, menuIds)

 const res:R<boolean> = await reqAssignedMenu({roleId: currentRoleId.value, menuIds})

  if (res && res.code === 200) {
    proxy.$modal.msgSuccess('权限分配成功')
    menuDialogVisible.value = false
  } else {
    proxy.$modal.msError('权限分配失败')
  }


}

/** 角色状态修改 */
function handleStatusChange(row: Role) {
  reqRoleUpdate({ roleId: row.roleId, status: row.status, switchStatus: true })
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value: any, type: any) {
  const nodes = menuRef.value?.store?.nodesMap ?? {} // 所有节点映射
  Object.values(nodes).forEach((node: any) => {
    node.expanded = value
  })
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value: any, type: string) {
  if (type == 'menu') {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
  } else if (type == 'dept') {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : [])
  }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value: any, type: string) {
  if (type == 'menu') {
    form.value.menuCheckStrictly = value ? true : false
  } else if (type == 'dept') {
    form.value.deptCheckStrictly = value ? true : false
  }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  if (!menuRef.value) return []
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys()
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}
</script>

<style scoped></style>
